import { GetterTree } from 'vuex';
import { States } from './states';

const getters: GetterTree<States, any> = {
    navContent(state: States): void {
        return state.navContent;
    },

    //根据cid获取对应cname
    cName: (state: States) => (cid: number) => {
        const node = state.routerMap[cid];
        if (node) {
            return node.name;
        }
        return '该大类ID不存在';
    },

    //判断该category是否为叶子节点
    isLeaf: (state: States) => (cid: number) => {
        const node = state.routerMap[cid];
        if (node) {
            const cidList = node.cidList;
            return !cidList || cidList.length === 0;
        }
        return true;
    },

    //获取父亲节点信息
    parentNode: (state: States, getters) => (cid: number) => {
        const node = state.routerMap[cid];
        if (node) {
            const pid = node.pid;
            const name = getters.cName(pid);
            return { name, cid: pid };
        }
        return { name: '软件学院', cid: 0 };
    },

    //获取面包屑路径
    routerParents: (state: States) => (cid: number) => {
        const pList: Array<any> = [];
        let currentId = cid;
        let flag = true;
        while (flag) {
            const node = state.routerMap[currentId];
            if (node) {
                const { name, pid } = node;
                pList.push({ name, cid: currentId });
                //如果父亲是-1, 代表已经到达根节点, 退出循环
                if (pid == -1) break;
                currentId = pid;
            } else {
                //路由表未加载完成入口
                pList.push({ name: '软件学院', cid: 0 });
                flag = false;
            }
        }
        pList.reverse();
        return pList;
    },

    //获取子大类列表
    routerChildren: (state: States, getters) => (cid: number) => {
        const node = state.routerMap[cid];
        if (node) {
            const rtnList: Array<any> = [];
            const cidList = node.cidList;
            cidList.forEach((children: number) => {
                rtnList.push({ name: getters.cName(children), cid: children });
            });
            return rtnList;
        }
        return [{ name: ' ', cid: -2 }];
    },

    //获取兄弟大类列表
    routerSiblings: (state: States, getters) => (cid: number) => {
        const node = state.routerMap[cid];
        if (node) {
            const pid = node.pid;
            return getters.routerChildren(pid);
        }
        return [];
    },

    //获取文章列表缓存页数
    articlePage(state: States): number {
        return state.articlePage;
    },
};
export default getters;
